package cn.iocoder.yudao.module.handguard.controller.admin.order;


import cn.iocoder.yudao.module.handguard.controller.admin.product.vo.ProductRespVO;
import cn.iocoder.yudao.module.handguard.controller.admin.productaccess.vo.ProductAccessResVO;
import cn.iocoder.yudao.module.handguard.controller.admin.productaccess.vo.ProductAccessRespVO;
import cn.iocoder.yudao.module.handguard.controller.app.applicationrecord.vo.ApplicationRecordPageReqVO;
import cn.iocoder.yudao.module.handguard.controller.app.applicationrecord.vo.ApplicationRecordRespVO;
import cn.iocoder.yudao.module.handguard.controller.app.orders.vo.OrdersInfoResVo;
import cn.iocoder.yudao.module.handguard.controller.app.orders.vo.OrdersResVo;
import cn.iocoder.yudao.module.handguard.controller.app.usertablesaudit.vo.UserAuditUpdateReqVO;
import cn.iocoder.yudao.module.handguard.convert.applicationrecord.ApplicationRecordConvert;
import cn.iocoder.yudao.module.handguard.convert.productaccess.ProductAccessConvert;
import cn.iocoder.yudao.module.handguard.dal.dataobject.applicationrecord.ApplicationRecordDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.product.ProductDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.productaccess.ProductAccessDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.user.UserDO;
import cn.iocoder.yudao.module.handguard.dal.mysql.user.MiniUserMapper;
import cn.iocoder.yudao.module.handguard.service.applicationrecord.ApplicationRecordService;
import cn.iocoder.yudao.module.handguard.service.product.ProductService;
import cn.iocoder.yudao.module.handguard.service.user.MiniUserService;
import cn.iocoder.yudao.module.handguard.service.usertablesaudit.UserTablesAuditService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;

import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.*;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUser;

import cn.iocoder.yudao.module.handguard.controller.admin.order.vo.*;
import cn.iocoder.yudao.module.handguard.dal.dataobject.order.OrderDO;
import cn.iocoder.yudao.module.handguard.convert.order.OrderConvert;
import cn.iocoder.yudao.module.handguard.service.order.OrderService;

@Tag(name = "管理后台 - 订单")
@RestController
@RequestMapping("/hutai/order")
@Validated
public class OrderController {

    @Resource
    private UserTablesAuditService userTablesAuditService;

    @Resource
    private MiniUserService miniUserService;

    @Resource
    private OrderService orderService;

    @Resource
    private ProductService productService;

    @Resource
    private MiniUserMapper userMapper;

    @Resource
    private ApplicationRecordService applicationRecordService;

    @GetMapping("/getMiniOrderUserInfo")
    @Operation(summary = "用户贷款记录")
    @Parameter(name = "id", description = "用户id", required = true, example = "1")
    public CommonResult<List<ApplicationRecordRespVO>> getMiniOrderUserInfo(Long id) {
        List<ApplicationRecordRespVO> respVOList = applicationRecordService.getApplicationRecordList(id);
        return success(respVOList);
    }


    @GetMapping("/get")
    @Operation(summary = "获得订单")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('hutai:order:query')")
    public CommonResult<OrderUserRespVO> getOrder(@RequestParam("id") Long id) {
        OrderUserRespVO orderUserRespVO = new OrderUserRespVO();
        orderUserRespVO = applicationRecordService.getUserAppllicationInfo(id);
        String productNameStr = "";
        //查询产品
        List<ProductRespVO> productRespVOList = new ArrayList<>();
        if (orderUserRespVO.getProductId().contains(",")) {
            String[] str = orderUserRespVO.getProductId().split(",");
            for (int i = 0; i < str.length; i++) {
                ProductRespVO productBaseVO = new ProductRespVO();
                ProductDO productDO = productService.getProduct(Long.valueOf(str[i]));
                BeanUtils.copyProperties(productDO, productBaseVO);
                productRespVOList.add(productBaseVO);
                productNameStr += productBaseVO.getProductName() + "、";
            }
        } else {
            ProductRespVO productBaseVO = new ProductRespVO();
            ProductDO productDO = productService.getProduct(Long.valueOf(orderUserRespVO.getProductId()));
            BeanUtils.copyProperties(productDO, productBaseVO);
            productRespVOList.add(productBaseVO);
            productNameStr = productBaseVO.getProductName();
        }
        orderUserRespVO.setProductNameStr(productNameStr);
        orderUserRespVO.setProduct(productRespVOList);

        //业务员
        UserResVo salesman = userMapper.getUserById(orderUserRespVO.getAgentId());
        //权证
        UserResVo warrant = userMapper.getUserById(orderUserRespVO.getWarrantId());
        orderUserRespVO.setSalesman(salesman);
        orderUserRespVO.setWarrant(warrant);

        return success(orderUserRespVO);
    }


    @GetMapping("/getOrderUserInfo")
    @Operation(summary = "获取订单个人信息")
    @Parameter(name = "id", description = "订单id", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('hutai:order:query')")
    public CommonResult<MemberUserBaseVO> getOrderUserInfo(Long id) {
        MemberUserBaseVO baseVO = orderService.getOrderUserInfo(id);
        return success(baseVO);
    }


    @GetMapping("/page")
    @Operation(summary = "获得订单分页")
    @PreAuthorize("@ss.hasPermission('hutai:order:query')")
    public CommonResult<PageResult<OrderRespVO>> getOrderPage(@Valid OrderPageReqVO pageVO) {
        PageResult<OrderDO> pageResult = orderService.getOrderPage(pageVO);
        return success(OrderConvert.INSTANCE.convertPage(pageResult));
    }


    //=================== 业务员端订单 ===================

    @GetMapping("/salesman-page")
    @Operation(summary = "业务员-订单列表")
    @PreAuthorize("@ss.hasPermission('hutai:order:query')")
    public CommonResult<PageResult<ApplicationRecordRespVO>> getApplicationRecordPage(@Valid ApplicationRecordPageReqVO pageVO) {
        //当前用户id
        Long userId = getLoginUser().getId();
        pageVO.setAgentId(userId);
        PageResult<ApplicationRecordDO> pageResult = applicationRecordService.getApplicationRecordPage(pageVO);
        PageResult<ApplicationRecordRespVO> result = ApplicationRecordConvert.INSTANCE.convertPage(pageResult);
        String productNameStr = "";
        //查询产品
        //List<ProductRespVO> productRespVOList = new ArrayList<>();
        for (ApplicationRecordRespVO respVO : result.getList()) {
            UserDO userDO = userMapper.selectById(respVO.getUserId());
            respVO.setApplicant(userDO.getName());

            if (respVO.getProductId().contains(",")) {
                String[] str = respVO.getProductId().split(",");
                for (int i = 0; i < str.length; i++) {
                    ProductRespVO productBaseVO = new ProductRespVO();
                    ProductDO productDO = productService.getProduct(Long.valueOf(str[i]));
                    BeanUtils.copyProperties(productDO, productBaseVO);
                    productNameStr += productBaseVO.getProductName() + "、";
                }
            } else {
                ProductRespVO productBaseVO = new ProductRespVO();
                ProductDO productDO = productService.getProduct(Long.valueOf(respVO.getProductId()));
                BeanUtils.copyProperties(productDO, productBaseVO);
                productNameStr = productBaseVO.getProductName();
            }
            respVO.setProductName(productNameStr);
        }
        return success(result);
    }

    @GetMapping("/common-list-info")
    @Operation(summary = "客户订单详情")
    @Parameter(name = "orderId", description = "订单id", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('hutai:order:query')")
    public CommonResult<OrdersInfoResVo> getCommonClientInfo(@RequestParam("orderId") Long orderId) {
        OrdersInfoResVo infoResVo = applicationRecordService.getAdminClientInfo(orderId);
        return success(infoResVo);
    }

    @GetMapping("/salesman-warrant-list-info")
    @Operation(summary = "业务员、权证-客户订单详情")
    @Parameter(name = "orderId", description = "订单id", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('hutai:order:query')")
    public CommonResult<OrdersInfoResVo> getClientInfo(@RequestParam("orderId") Long orderId) {
        OrdersInfoResVo infoResVo = applicationRecordService.getSalesmanWarrantClientInfo(orderId);
        return success(infoResVo);
    }


    @GetMapping("/getWarrantOrderPage")
    @Operation(summary = "权证-获得订单分页")
    @PreAuthorize("@ss.hasPermission('hutai:order:query')")
    public CommonResult<PageResult<ApplicationRecordRespVO>> getWarrantOrderPage(@Valid ApplicationRecordPageReqVO pageVO) {
        //当前用户id
        Long userId = getLoginUser().getId();
        pageVO.setWarrant_id(userId);
        PageResult<ApplicationRecordDO> pageResult = applicationRecordService.getApplicationRecordPage(pageVO);
        PageResult<ApplicationRecordRespVO> result = ApplicationRecordConvert.INSTANCE.convertPage(pageResult);
        String productNameStr = "";
        //查询产品
        //List<ProductRespVO> productRespVOList = new ArrayList<>();
        for (ApplicationRecordRespVO respVO : result.getList()) {
            UserDO userDO = userMapper.selectById(respVO.getUserId());
            respVO.setApplicant(userDO.getName());

            if (respVO.getProductId().contains(",")) {
                String[] str = respVO.getProductId().split(",");
                for (int i = 0; i < str.length; i++) {
                    ProductRespVO productBaseVO = new ProductRespVO();
                    ProductDO productDO = productService.getProduct(Long.valueOf(str[i]));
                    BeanUtils.copyProperties(productDO, productBaseVO);
                    productNameStr += productBaseVO.getProductName() + "、";
                }
            } else {
                ProductRespVO productBaseVO = new ProductRespVO();
                ProductDO productDO = productService.getProduct(Long.valueOf(respVO.getProductId()));
                BeanUtils.copyProperties(productDO, productBaseVO);
                productNameStr = productBaseVO.getProductName();
            }
            respVO.setProductName(productNameStr);


            return success(result);
        }
        return success(new PageResult<>());
    }


    @PostMapping("/agent/reject")
    @Operation(summary = "业务员-资料审核-驳回")
    public CommonResult<Boolean> updateApplicationAudit(@Valid @RequestBody UserAuditUpdateReqVO updateReqVO) {
        userTablesAuditService.updateApplicationAudit(updateReqVO);
        return success(true);
    }


    @GetMapping("/getCheckProductAccess")
    @Operation(summary = "业务员资料-产品准入匹配")
    public CommonResult<List<ProductAccessResVO>> getCheckProductAccess(String orderId) throws Exception {
        //当前用户id
        List<ProductAccessDO> list = miniUserService.getCheckProductAccess(orderId);
        return success(ProductAccessConvert.INSTANCE.convertLists(list));
    }

}
